package com.jialanmo.zhihudaily.ui.main;

import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.jialanmo.helper.OnItemClickListener;
import com.jialanmo.helper.viewpager.BasePagerAdapter;
import com.jialanmo.zhihudaily.R;
import com.jialanmo.zhihudaily.data.model.TopStory;

import java.util.ArrayList;
import java.util.List;

public final class TopStoryPagerAdapter extends BasePagerAdapter<TopStory> {

    private final List<TopStory> mData = new ArrayList<>();
    private final SparseArray<View> mViews = new SparseArray<>();

    private final OnItemClickListener mOnItemClickListener;

    public TopStoryPagerAdapter(OnItemClickListener onItemClickListener) {
        mOnItemClickListener = onItemClickListener;
    }

    @Override
    public List<TopStory> getData() {
        return mData;
    }

    @Override
    public int getCount() {
        return mData.size();
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return mViews.get(object.hashCode()) == view;
    }

    @Override
    public TopStory instantiateItem(ViewGroup container, final int position) {
        TopStory data = mData.get(position);
        View view = mViews.get(data.hashCode());
        if (view == null) {
            view = LayoutInflater.from(container.getContext()).inflate(R.layout.fragment_main_topsotry_viewpager_item, container, false);
            ((TextView) view.findViewById(R.id.fragment_main_topstory_viewpager_item_textview_title)).setText(mData.get(position).getTitle());
            Glide.with(container.getContext()).load(mData.get(position).getImage()).into((ImageView) view.findViewById(R.id.fragment_main_topstory_viewpager_item_imageview_image));
            if (mOnItemClickListener != null) {
                view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mOnItemClickListener.onItemClick(position);
                    }
                });
            }
            mViews.put(data.hashCode(), view);
        }
        container.addView(view);
        return data;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView(mViews.get(object.hashCode()));
    }

    @Override
    public int getItemPosition(Object object) {
        TopStory topStory = (TopStory) object;
        int index = mData.indexOf(topStory);
        return index == -1 ? POSITION_NONE : index;
    }

    @Override
    public void resetData(List<TopStory> data) {
        mData.clear();
        mViews.clear();
        mData.addAll(data);
        notifyDataSetChanged();
    }
}